package com.raincat.tools.permissiontools;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.raincat.tools.R;

import java.util.ArrayList;
import java.util.List;

/**
 * <pre>
 *     author : RainCat
 *     org    : Shenzhen JingYu Network Technology Co., Ltd.
 *     e-mail : nining377@gmail.com
 *     time   : 2020/05/13
 *     desc   : 获取权限
 *     version: 1.0
 * </pre>
 */
public class PermissionProxyActivity extends Activity {
    private final static int REQUEST_CODE_ASK_PERMISSIONS = 123;

    private Context context;
    private String dialogMessage;
    private String[] permissionsList;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;

        dialogMessage = getIntent().getStringExtra("message");
        permissionsList = getIntent().getStringArrayExtra("permissions");
        if (permissionsList == null || permissionsList.length == 0) {
            if (getIntent().getStringExtra("url") != null)
                checkInstallPermission();
            else
                finish();
        } else
            checkPermission();
    }

    /**
     * 检查权限
     */
    private void checkPermission() {
        // Android 6.0以上才用询问权限
        if (Build.VERSION.SDK_INT < 23) {
            PermissionProxyListenerManager.getInstance().onPermissionGet(true);
            finish();
            return;
        }

        List<String> permissionsNeed = new ArrayList<>();
        for (String permission : permissionsList) {
            if (ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED)
                permissionsNeed.add(permission);
        }

        if (permissionsNeed.size() != 0) {
            showMessageDialog(permissionsNeed);
        } else {
            PermissionProxyListenerManager.getInstance().onPermissionGet(true);
            finish();
        }
    }

    public void checkInstallPermission() {
        new AlertDialog.Builder(context, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT)
                .setCancelable(false)
                .setTitle(getString(R.string.permission))
                .setMessage(dialogMessage)
                .setPositiveButton("前往设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Uri packageURI = Uri.parse("package:" + context.getPackageName());
                        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
                        startActivityForResult(intent, REQUEST_CODE_ASK_PERMISSIONS);
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                PermissionProxyListenerManager.getInstance().onPermissionGet(false);
                finish();
            }
        }).show();
    }

    @SuppressLint("Override")
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_CODE_ASK_PERMISSIONS) {
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    PermissionProxyListenerManager.getInstance().onPermissionGet(false);
                    return;
                }
            }
            PermissionProxyListenerManager.getInstance().onPermissionGet(true);
            finish();
        }
    }

    @Override
    public void finish() {
        super.finish();
        PermissionProxyListenerManager.getInstance().onDestroy();
        overridePendingTransition(0, 0);
    }

    private void showMessageDialog(final List<String> permissionsNeed) {
        if (dialogMessage != null && dialogMessage.length() != 0) {
            new AlertDialog.Builder(context, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT)
                    .setCancelable(false)
                    .setTitle(getString(R.string.permission))
                    .setMessage(dialogMessage)
                    .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            ActivityCompat.requestPermissions((Activity) context, permissionsNeed.toArray(new String[0]), REQUEST_CODE_ASK_PERMISSIONS);
                        }
                    }).show();
        } else {
            ActivityCompat.requestPermissions((Activity) context, permissionsNeed.toArray(new String[0]), REQUEST_CODE_ASK_PERMISSIONS);
        }
    }
}
